import pygame
import sys
import json
import os
from pygame.locals import *

# 初始化Pygame
pygame.init()
pygame.display.set_caption("互动桌面宠物")

# 配置参数
SCREEN_WIDTH, SCREEN_HEIGHT = 200, 200  # 宠物窗口大小
FPS = 10  # 动画帧率
PET_STATES = ["idle", "happy", "hungry"]  # 宠物状态
DATA_FILE = "pet_data.json"  # 状态保存文件

# 加载资源（这里用颜色块模拟，实际项目替换为序列帧图片）
class PetResources:
    def __init__(self):
        # 实际开发中替换为加载图片帧
        self.images = {
            "idle": [pygame.Surface((100, 100)) for _ in range(3)],
            "happy": [pygame.Surface((100, 100)) for _ in range(3)],
            "hungry": [pygame.Surface((100, 100)) for _ in range(3)]
        }
        # 给不同状态的帧上色（模拟不同动画）
        self.images["idle"][0].fill((255, 255, 0))    # 黄色-Idle1
        self.images["idle"][1].fill((255, 240, 0))    # 浅黄-Idle2
        self.images["idle"][2].fill((255, 220, 0))    # 深黄-Idle3
        self.images["happy"][0].fill((0, 255, 0))     # 绿色-Happy1
        self.images["happy"][1].fill((0, 240, 0))     # 浅绿-Happy2
        self.images["happy"][2].fill((0, 220, 0))     # 深绿-Happy3
        self.images["hungry"][0].fill((255, 0, 0))    # 红色-Hungry1
        self.images["hungry"][1].fill((240, 0, 0))    # 深红-Hungry2
        self.images["hungry"][2].fill((220, 0, 0))    # 暗红-Hungry3

# 宠物类（核心逻辑）
class Pet:
    def __init__(self):
        self.resources = PetResources()
        self.state = "idle"  # 初始状态
        self.frame_index = 0  # 当前动画帧索引
        self.mood = 50  # 心情值（0-100）
        self.hunger = 50  # 饱食度（0-100）
        self.position = (100, 100)  # 初始位置
        self.dragging = False  # 是否被拖拽
        self.drag_offset = (0, 0)  # 拖拽偏移量
        self.load_data()  # 加载保存的状态

    # 加载保存的宠物数据
    def load_data(self):
        if os.path.exists(DATA_FILE):
            with open(DATA_FILE, "r") as f:
                data = json.load(f)
                self.position = tuple(data["position"])
                self.mood = data["mood"]
                self.hunger = data["hunger"]
                self.update_state()  # 根据加载的状态更新动画

    # 保存宠物数据
    def save_data(self):
        data = {
            "position": self.position,
            "mood": self.mood,
            "hunger": self.hunger
        }
        with open(DATA_FILE, "w") as f:
            json.dump(data, f)

    # 更新宠物状态（根据心情和饱食度）
    def update_state(self):
        if self.hunger < 30:
            self.state = "hungry"
        elif self.mood > 70:
            self.state = "happy"
        else:
            self.state = "idle"

    # 更新动画帧
    def update_animation(self):
        self.frame_index = (self.frame_index + 1) % len(self.resources.images[self.state])

    # 处理鼠标事件
    def handle_event(self, event):
        if event.type == MOUSEBUTTONDOWN:
            if event.button == 1:  # 左键点击
                mouse_pos = pygame.mouse.get_pos()
                # 检查是否点击到宠物（简单碰撞检测）
                pet_rect = self.get_rect()
                if pet_rect.collidepoint(mouse_pos):
                    self.dragging = True
                    self.drag_offset = (
                        pet_rect.topleft[0] - mouse_pos[0],
                        pet_rect.topleft[1] - mouse_pos[1]
                    )
                    # 点击增加心情值
                    self.mood = min(100, self.mood + 10)
                    self.update_state()

        elif event.type == MOUSEMOTION:
            if self.dragging:
                # 拖拽移动宠物
                mouse_pos = pygame.mouse.get_pos()
                self.position = (
                    mouse_pos[0] + self.drag_offset[0],
                    mouse_pos[1] + self.drag_offset[1]
                )

        elif event.type == MOUSEBUTTONUP:
            if event.button == 1:  # 左键释放
                self.dragging = False

        # 右键点击喂食（增加饱食度）
        elif event.type == MOUSEBUTTONDOWN and event.button == 3:
            self.hunger = min(100, self.hunger + 20)
            self.update_state()

    # 获取宠物碰撞矩形
    def get_rect(self):
        img = self.resources.images[self.state][self.frame_index]
        return img.get_rect(center=self.position)

    # 绘制宠物
    def draw(self, screen):
        current_img = self.resources.images[self.state][self.frame_index]
        screen.blit(current_img, self.get_rect())

    # 随时间更新状态（饥饿度缓慢下降）
    def update_over_time(self):
        self.hunger = max(0, self.hunger - 0.01)
        self.mood = max(0, self.mood - 0.005)
        self.update_state()

# 主程序
def main():
    # 创建透明窗口（无边框、置顶）
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.NOFRAME | pygame.SRCALPHA)
    pygame.display.set_caption("桌面宠物")
    clock = pygame.time.Clock()
    pet = Pet()

    running = True
    while running:
        screen.fill((0, 0, 0, 0))  # 透明背景

        # 事件处理
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
            pet.handle_event(event)

        # 更新逻辑
        pet.update_animation()
        pet.update_over_time()

        # 绘制
        pet.draw(screen)
        pygame.display.flip()
        clock.tick(FPS)

    # 退出前保存数据
    pet.save_data()
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()
